import * as mqtt from 'mqtt/dist/mqtt.min.js'
//mqtt客户端对象
export const mqttClient = ref()

//初始化操作
export const init = (url, options) => {
	mqttClient.value = mqtt.connect(url, options) //连接mqtt
	//报错
	mqttClient.value.on('error', (error) => {
		console.log('mqtt连接报错')
		console.log(error)
	})
	//重连
	mqttClient.value.on('reconnect', (error) => {
		console.log('mqtt重连')
		console.log(error)
	})
}

//连接
// export const link = (topics) => {
// 	//连接成功
// 	mqttClient.value.on('connect', () => {
// 		console.log('mqtt连接成功')
// 		//判断是否为数组
// 		if (Array.isArray(topics)) {
// 			//订阅频道
// 			for (let topic in topics) {
// 				subscribes(topic)
// 			}
// 		}
// 	})
// }

//接收消息
export const link = (callback) => {
	mqttClient.value.on('connect', callback)
}

//订阅
export const subscribes = (topics) => {
	if (Array.isArray(topics)) {
		//订阅频道
		topics.forEach((topic) => {
			subscribe(topic)
		})
	}
}

//订阅
export const subscribe = (topic) => {
	mqttClient.value.subscribe(topic, (error) => {
		if (!error) {
			console.log(topic, '订阅成功')
		} else {
			console.log(topic, '订阅失败')
		}
	})
}

//取消订阅
export const unSubscribes = (topic) => {
	mqttClient.value.unsubscribe(topic, (error) => {
		if (!error) {
			console.log(topic, '取消订阅成功')
		} else {
			console.log(topic, '取消订阅失败')
		}
	})
}

//接收消息
export const getMessage = (callback) => {
	mqttClient.value.on('message', callback)
}

//关闭连接
export const close = () => {
	console.log('关闭连接')
	mqttClient.value.end()
	mqttClient.value = null
}
